package com.xunshangwang.pinhaohuo.transformation;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.v4.content.ContextCompat;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

/**
 * Created by xzp on 15/11/26.
 */
public class RoundedTransformation extends BitmapTransformation{
    int mRoundedSize,mBorderSize;
    int mBorderColor;
    public RoundedTransformation(Context context,int roundedResId) {
        this(context, roundedResId, -1, -1);
    }
    public RoundedTransformation(Context context,int roundedResId,int borderResId,int colorResId) {
        super(context);
        mRoundedSize=context.getResources().getDimensionPixelSize(roundedResId);
        if(borderResId!=-1){
            mBorderSize=context.getResources().getDimensionPixelSize(borderResId);
        }else {
            mBorderSize=0;
        }
        if(colorResId!=-1){
            mBorderColor = ContextCompat.getColor(context,colorResId);
        }else{
            mBorderColor= Color.WHITE;
        }

    }
    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Bitmap bitmap=pool.get(outWidth,outHeight, Bitmap.Config.ARGB_8888);
        if(bitmap==null){
            bitmap=Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888);
        }
        Canvas canvas=new Canvas(bitmap);
        if(mBorderSize>0){
            Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(mBorderColor);
            RectF rectF=new RectF(0,0,outWidth,outHeight);
            canvas.drawRoundRect(rectF,mRoundedSize,mRoundedSize,paint);
        }
        float scale = Math.min((outWidth-mBorderSize) * 1.0f / toTransform.getWidth(), (outHeight-mBorderSize)
                * 1.0f / toTransform.getHeight());
        BitmapShader shader = new BitmapShader(toTransform, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        Matrix matrix= new Matrix();
        if(scale<0)
            scale=1;
        matrix.setScale(scale,scale);
        shader.setLocalMatrix(matrix);
        Paint bitmapPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        bitmapPaint.setShader(shader);
        RectF bitmapRectF=new RectF(mBorderSize,mBorderSize,outWidth-mBorderSize,outHeight-mBorderSize);
        canvas.drawRoundRect(bitmapRectF,mRoundedSize,mRoundedSize,bitmapPaint);
        return bitmap;
    }

    @Override
    public String getId() {
        return "com.xunshangwang.pinhaohuo.transformation.RoundedTransformation";
    }
}
